package com.enation.app.javashop.consumer.shop.member;

import com.dag.eagleshop.core.account.model.dto.account.AccountDTO;
import com.dag.eagleshop.core.account.model.dto.account.OpenAccountDTO;
import com.dag.eagleshop.core.account.model.dto.member.MemberDTO;
import com.dag.eagleshop.core.account.model.dto.member.OpenMemberDTO;
import com.dag.eagleshop.core.account.model.dto.member.OpenMemberIdentityDTO;
import com.dag.eagleshop.core.account.model.enums.AccountTypeEnum;
import com.dag.eagleshop.core.account.model.enums.IdentityTypeEnum;
import com.dag.eagleshop.core.account.model.enums.NatureEnum;
import com.dag.eagleshop.core.account.service.AccountManager;
import com.enation.app.javashop.consumer.core.event.MemberRegisterEvent;
import com.enation.app.javashop.core.base.message.MemberRegisterMsg;
import com.enation.app.javashop.core.member.model.dos.Member;
import com.enation.app.javashop.core.member.service.MemberManager;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 会员账户注册
 * @author 孙建
 */
@Service
public class MemberAccountConsumer implements MemberRegisterEvent {

    @Autowired
    private AccountManager accountManager;
    @Autowired
    private MemberManager memberManager;

    @Override
    public void memberRegister(MemberRegisterMsg memberRegisterMsg) {
        // 开通会员
        Member messageMember = memberRegisterMsg.getMember();
        OpenMemberDTO openMemberDTO = new OpenMemberDTO();
        openMemberDTO.setMobile(messageMember.getMobile());
        openMemberDTO.setMemberName(messageMember.getNickname());
        // 设置会员身份
        OpenMemberIdentityDTO memberIdentityDTO = new OpenMemberIdentityDTO();
        memberIdentityDTO.setIdentityType(IdentityTypeEnum.BUYER.getIndex());
        memberIdentityDTO.setIdentityName(IdentityTypeEnum.BUYER.getText());
        openMemberDTO.setIdentityList(Lists.newArrayList(memberIdentityDTO));
        MemberDTO memberDTO = accountManager.openMember(openMemberDTO);

        // 开通账户
        OpenAccountDTO openAccountDTO = new OpenAccountDTO();
        openAccountDTO.setAccountType(AccountTypeEnum.MEMBER_MASTER.getIndex());
        openAccountDTO.setAccountTypeName(AccountTypeEnum.MEMBER_MASTER.getText());
        openAccountDTO.setMemberId(memberDTO.getId());
        openAccountDTO.setNature(NatureEnum.PERSONAL.getIndex());
        openAccountDTO.setOperatorName(messageMember.getUname());
        AccountDTO accountDTO = accountManager.openAccount(openAccountDTO);

        // 更新本地会员和账户会员映射关系表
        messageMember.setAccountMemberId(accountDTO.getMemberId());
        memberManager.edit(messageMember, messageMember.getMemberId());
    }
}
